package protocol

import (
	"fmt"
	"strings"
	"time"
)

// SIPMessage SIP协议消息结构
type SIPMessage struct {
	Method      string            // SIP方法 (INVITE, REGISTER, MESSAGE, BYE, etc.)
	RequestURI  string            // 请求URI
	SIPVersion  string            // SIP版本 (SIP/2.0)
	Headers     map[string]string // SIP头部字段
	Body        string            // 消息体
	From        string            // From字段
	To          string            // To字段
	CallID      string            // Call-ID字段
	CSeq        string            // CSeq字段
	Via         string            // Via字段
	MaxForwards string            // Max-Forwards字段
	Contact     string            // Contact字段
	UserAgent   string            // User-Agent字段
	ContentType string            // Content-Type字段
	ContentLength string          // Content-Length字段
}

// SIPMessageType SIP消息类型常量
const (
	SIPMethodINVITE   = "INVITE"
	SIPMethodREGISTER = "REGISTER"
	SIPMethodMESSAGE  = "MESSAGE"
	SIPMethodBYE      = "BYE"
	SIPMethodACK      = "ACK"
	SIPMethodCANCEL   = "CANCEL"
	SIPMethodOPTIONS  = "OPTIONS"
)

// ParseSIPMessage 解析SIP协议消息
func ParseSIPMessage(data []byte) (*SIPMessage, error) {
	message := &SIPMessage{
		Headers: make(map[string]string),
	}

	lines := strings.Split(string(data), "\r\n")
	if len(lines) == 1 {
		// 如果没有CRLF，尝试用LF分割
		lines = strings.Split(string(data), "\n")
	}

	// 解析起始行
	if len(lines) == 0 {
		return nil, fmt.Errorf("空消息")
	}

	startLine := strings.TrimSpace(lines[0])
	startParts := strings.Fields(startLine)
	if len(startParts) < 3 {
		return nil, fmt.Errorf("无效的起始行: %s", startLine)
	}

	message.Method = startParts[0]
	message.RequestURI = startParts[1]
	message.SIPVersion = startParts[2]

	// 解析头部字段
	for i := 1; i < len(lines); i++ {
		line := strings.TrimSpace(lines[i])
		if line == "" {
			// 空行表示头部结束
			break
		}

		// 处理多行头部字段
		if i+1 < len(lines) && (lines[i+1][0] == ' ' || lines[i+1][0] == '\t') {
			line += " " + strings.TrimSpace(lines[i+1])
			i++
		}

		parts := strings.SplitN(line, ":", 2)
		if len(parts) == 2 {
			headerName := strings.TrimSpace(parts[0])
			headerValue := strings.TrimSpace(parts[1])
			
			message.Headers[headerName] = headerValue
			
			// 设置常用字段
			switch headerName {
			case "From":
				message.From = headerValue
			case "To":
				message.To = headerValue
			case "Call-ID":
				message.CallID = headerValue
			case "CSeq":
				message.CSeq = headerValue
			case "Via":
				message.Via = headerValue
			case "Max-Forwards":
				message.MaxForwards = headerValue
			case "Contact":
				message.Contact = headerValue
			case "User-Agent":
				message.UserAgent = headerValue
			case "Content-Type":
				message.ContentType = headerValue
			case "Content-Length":
				message.ContentLength = headerValue
			}
		}
	}

	// 解析消息体
	if message.ContentLength != "" {
		contentLen := 0
		fmt.Sscanf(message.ContentLength, "%d", &contentLen)
		if contentLen > 0 {
			// 查找消息体开始位置
			bodyStart := 0
			for i, line := range lines {
				if strings.TrimSpace(line) == "" {
					bodyStart = i + 1
					break
				}
			}
			
			if bodyStart > 0 && bodyStart < len(lines) {
				message.Body = strings.Join(lines[bodyStart:], "\r\n")
			}
		}
	}

	return message, nil
}

// BuildSIPMessage 构建SIP协议消息
func BuildSIPMessage(method, requestURI, from, to, callID, cseq string, body string) []byte {
	var message strings.Builder

	// 起始行
	message.WriteString(fmt.Sprintf("%s %s SIP/2.0\r\n", method, requestURI))

	// Via字段
	message.WriteString(fmt.Sprintf("Via: SIP/2.0/UDP %s;branch=z9hG4bK%d;rport\r\n", 
		"127.0.0.1:5060", time.Now().UnixNano()))

	// Max-Forwards
	message.WriteString("Max-Forwards: 70\r\n")

	// From
	message.WriteString(fmt.Sprintf("From: %s\r\n", from))

	// To
	message.WriteString(fmt.Sprintf("To: %s\r\n", to))

	// Call-ID
	message.WriteString(fmt.Sprintf("Call-ID: %s\r\n", callID))

	// CSeq
	message.WriteString(fmt.Sprintf("CSeq: %s %s\r\n", cseq, method))

	// Contact
	message.WriteString(fmt.Sprintf("Contact: %s\r\n", from))

	// User-Agent
	message.WriteString("User-Agent: GB28181-Server/1.0\r\n")

	// 如果有消息体
	if body != "" {
		message.WriteString("Content-Type: application/xml\r\n")
		message.WriteString(fmt.Sprintf("Content-Length: %d\r\n", len(body)))
		message.WriteString("\r\n")
		message.WriteString(body)
	} else {
		message.WriteString("Content-Length: 0\r\n")
		message.WriteString("\r\n")
	}

	return []byte(message.String())
}

// BuildSIPResponse 构建SIP响应消息
func BuildSIPResponse(statusCode int, statusText, via, from, to, callID, cseq string, body string) []byte {
	var message strings.Builder

	// 起始行
	message.WriteString(fmt.Sprintf("SIP/2.0 %d %s\r\n", statusCode, statusText))

	// Via
	if via != "" {
		message.WriteString(fmt.Sprintf("Via: %s\r\n", via))
	}

	// From
	message.WriteString(fmt.Sprintf("From: %s\r\n", from))

	// To
	message.WriteString(fmt.Sprintf("To: %s\r\n", to))

	// Call-ID
	message.WriteString(fmt.Sprintf("Call-ID: %s\r\n", callID))

	// CSeq
	message.WriteString(fmt.Sprintf("CSeq: %s\r\n", cseq))

	// Contact
	message.WriteString(fmt.Sprintf("Contact: %s\r\n", from))

	// User-Agent
	message.WriteString("User-Agent: GB28181-Server/1.0\r\n")

	// 如果有消息体
	if body != "" {
		message.WriteString("Content-Type: application/xml\r\n")
		message.WriteString(fmt.Sprintf("Content-Length: %d\r\n", len(body)))
		message.WriteString("\r\n")
		message.WriteString(body)
	} else {
		message.WriteString("Content-Length: 0\r\n")
		message.WriteString("\r\n")
	}

	return []byte(message.String())
}

// ExtractDeviceIDFromSIPURI 从SIP URI中提取设备ID
func ExtractDeviceIDFromSIPURI(sipURI string) (string, error) {
	// SIP URI格式: sip:device_id@ip:port
	if !strings.HasPrefix(sipURI, "sip:") {
		return "", fmt.Errorf("无效的SIP URI格式: %s", sipURI)
	}

	uri := strings.TrimPrefix(sipURI, "sip:")
	parts := strings.Split(uri, "@")
	if len(parts) < 1 {
		return "", fmt.Errorf("无法解析SIP URI: %s", sipURI)
	}

	return parts[0], nil
}

// IsSIPMessage 判断是否为SIP协议消息
func IsSIPMessage(data []byte) bool {
	strData := string(data)
	return strings.HasPrefix(strData, "INVITE ") ||
		strings.HasPrefix(strData, "REGISTER ") ||
		strings.HasPrefix(strData, "MESSAGE ") ||
		strings.HasPrefix(strData, "BYE ") ||
		strings.HasPrefix(strData, "ACK ") ||
		strings.HasPrefix(strData, "CANCEL ") ||
		strings.HasPrefix(strData, "OPTIONS ") ||
		strings.HasPrefix(strData, "SIP/2.0 ")
}

// ConvertGB28181ToSIP 将GB28181消息转换为SIP MESSAGE格式
func ConvertGB28181ToSIP(gbMessage []byte, from, to, callID string) []byte {
	cseq := fmt.Sprintf("%d", time.Now().Unix())
	requestURI := to
	
	return BuildSIPMessage(SIPMethodMESSAGE, requestURI, from, to, callID, cseq, string(gbMessage))
}

// ConvertSIPToGB28181 从SIP MESSAGE中提取GB28181消息
func ConvertSIPToGB28181(sipMessage *SIPMessage) ([]byte, error) {
	if sipMessage.Method != SIPMethodMESSAGE {
		return nil, fmt.Errorf("非MESSAGE类型的SIP消息")
	}

	if sipMessage.Body == "" {
		return nil, fmt.Errorf("SIP消息体为空")
	}

	return []byte(sipMessage.Body), nil
}